using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows.Data;

namespace Honest.MES.WPF.ViewModels
{
    public class MenuItemGroupConverter : IValueConverter
    {
        public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture)
        {
            if (value is ObservableCollection<ModuleMenuItem> menuItems)
            {
                // 分离单模块组菜单项和普通菜单项
                var singleModuleGroupItems = menuItems
                    .Where(item => !item.IsCategory && item.IsSingleModuleGroup)
                    .ToList();

                // 对普通菜单项按GroupName分组
                var groupedItems = menuItems
                    .Where(item => !item.IsCategory && !item.IsSingleModuleGroup && !string.IsNullOrEmpty(item.GroupName))
                    .GroupBy(item => item.GroupName)
                    .OrderBy(group => group.Key)
                    .Select(group => new ModuleMenuItemGroup
                    {
                        GroupName = group.Key,
                        Items = new ObservableCollection<ModuleMenuItem>(group.ToList())
                    })
                    .ToList<object>();

                // 将单模块组菜单项添加到结果列表的开头
                groupedItems.InsertRange(0, singleModuleGroupItems.Cast<object>());

                return groupedItems;
            }
            return value;
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }

    public class ModuleMenuItemGroup
    {
        public string GroupName { get; set; }
        public ObservableCollection<ModuleMenuItem> Items { get; set; }
    }
}